package cn.itcast.servlet;

import cn.itcast.domain.User;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;

@WebServlet("/listUserServlet")
public class ListUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //读取本地文件
        BufferedReader br = new BufferedReader(new FileReader("D:/user.txt"));
        String s;
        //新建集合，储存数据
        ArrayList<User> list = new ArrayList<>();
        //将读取到的数据存入list
        while ((s = br.readLine())!=null){
            //按，分割
            String[] strings = s.split(",");
            //封装信息
            list.add(new User(strings[0],Integer.valueOf(strings[1]),Integer.valueOf(strings[2])));
        }

        //获取打印流
        PrintWriter pw = response.getWriter();
        //封装完成，遍历集合，查看学生信息
        for (User user : list) {
            pw.println(user.getUsername()+"  "+user.getAge()+"  "+user.getScore());
            pw.write("<br/>");
        }
        //查看五秒后跳转
        response.getWriter().print("信息显示完毕，五秒后跳转");
        response.setHeader("Refresh","5;"+super.getServletContext().getContextPath()+"/index.html");
    }
}
